# HTTP协议封装服务器
import socket


def get_personal_info_html():
    """返回包含个人信息的HTML文档"""
    return """<!DOCTYPE html>
<html>
<head>
    <title>个人信息</title>
</head>
<body>
    <h1>我的个人信息</h1>
    <p>姓名: 刘禾钰</p>
    <p>学号: 202271134250</p>
    <p>专业: 信计</p>
</body>
</html>"""


def run_http_server():
    # 创建TCP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置套接字选项，允许地址重用
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定地址和端口
    server_address = ('localhost', 8080)
    server_socket.bind(server_address)

    # 开始监听，最大连接数为1
    server_socket.listen(1)
    print(f"服务器启动，监听地址: {server_address}")

    while True:
        # 接受客户端连接
        connection_socket, client_address = server_socket.accept()
        print(f"接受来自 {client_address} 的连接")

        try:
            # 接收客户端请求
            request = connection_socket.recv(1024).decode()
            print(f"收到请求:\n{request}")

            # 准备HTTP响应
            html_content = get_personal_info_html()
            response_header = "HTTP/1.1 200 OK\r\n"
            response_header += "Content-Type: text/html; charset=utf-8\r\n"
            response_header += f"Content-Length: {len(html_content)}\r\n"
            response_header += "Connection: close\r\n\r\n"

            # 发送响应
            response = response_header + html_content
            connection_socket.sendall(response.encode())

        except Exception as e:
            print(f"处理请求时出错: {e}")
        finally:
            # 关闭连接
            connection_socket.close()


if __name__ == "__main__":
    run_http_server()
